package com.newa.actions;

import java.io.File;
import java.util.StringTokenizer;

import org.apache.commons.io.FileUtils;
import org.apache.log4j.Logger;
import org.apache.struts2.ServletActionContext;
import org.hibernate.Session;

import com.newa.beans.Work;
import com.newa.dao.DAOWorks;
import com.newa.listeners.Listener;
import com.newa.utils.HibUtil;
import com.opensymphony.xwork2.ActionSupport;

public class deleteWork extends ActionSupport {
	private Logger LOG = Logger.getLogger(deleteWork.class);
	private static final long serialVersionUID = 1L;
	private int id;
	private int work_id;

	@Override
	public String execute() throws Exception {
		Session session = HibUtil.getSessionFactory().openSession();
		DAOWorks daow = new DAOWorks(session);
		try {

			Work work = daow.getWorkById(work_id);
			String lLink = work.getLOGO_LINK();
			String phLinks = work.getPHOTO_LINKS();
			String lphLinks = work.getLPHOTO_LINKS();
			daow.deleteWorkById(work_id);
			if (lLink != null && lLink != "") {
				File d = new File(lLink);
				d.delete();
			}
			if (phLinks != null && phLinks != "") {
				StringTokenizer tok = new StringTokenizer(phLinks, ";");
				StringTokenizer ltok = new StringTokenizer(lphLinks, ";");
				while (tok.hasMoreElements()) {
					String pa = (String) tok.nextElement();
					String lpa = ltok.nextToken();
					File ld = new File(lpa);
					File d = new File(pa);
					ld.delete();
					d.delete();
				}
			}

		} catch (Exception e) {
			LOG.warn(e);
			throw new RuntimeException(e);
		} finally {
			daow.closeSession().close();
		}
		return "success";
	}

	public int getId() {
		return id;
	}

	public void setId(int id) {
		this.id = id;
	}

	public int getWork_id() {
		return work_id;
	}

	public void setWork_id(int work_id) {
		this.work_id = work_id;
	}

}
